<template>
  <div class="interview-analysis-container">
    <div class="page-header">
      <a-button type="text" @click="goBack" style="margin-right: 16px">
        <template #icon><arrow-left-outlined /></template>
        返回
      </a-button>
      <h2 v-if="analysisData">面试分析报告</h2>
    </div>

    <a-spin :spinning="loading" tip="加载分析数据中...">
      <div v-if="analysisData" class="analysis-content-wrapper">
        <!-- 顶部标签页 -->
        <a-tabs v-model:activeKey="activeTab" class="analysis-tabs" :tab-bar-style="{ zIndex: 1 }">
          <!-- 面试概览标签页 -->
          <a-tab-pane key="summary" tab="面试概览">
            <div class="analysis-content">
              <!-- 左侧分析面板 -->
              <div class="left-analysis-panel">
                <!-- 技术能力评分卡片 -->
                <div class="scores-overview">
                  <h3>技术面试结果</h3>
                  <div class="result-summary">
                    <a-alert
                      :type="isInterviewPassed ? 'success' : 'error'"
                      :message="isInterviewPassed ? '面试结果：通过' : '面试结果：未通过'"
                      :description="
                        isInterviewPassed
                          ? '候选人技术能力达到要求标准'
                          : '候选人技术能力未达到要求标准'
                      "
                      show-icon
                      style="margin-bottom: 16px"
                    />
                    <div class="total-score">
                      <span>总分：</span>
                      <span
                        class="score-number"
                        :style="{ color: getTotalScoreColor(analysisData.totalScore) }"
                        >{{ analysisData.totalScore }}</span
                      >
                      <span class="score-unit">/100</span>
                    </div>
                  </div>
                  <a-row :gutter="16">
                    <a-col :span="12" v-for="(score, index) in parsedScores" :key="index">
                      <a-card class="score-card">
                        <div class="score-header">
                          <span class="question-index">问题 {{ index + 1 }}</span>
                          <a-tag :color="getScoreColor(score)">{{ score }} 分</a-tag>
                        </div>
                        <div class="score-bar-container">
                          <div
                            class="score-bar"
                            :style="{
                              width: `${score * 10}%`,
                              backgroundColor: getScoreColor(score),
                            }"
                          ></div>
                          <div class="score-threshold" :style="{ left: '60%' }"></div>
                        </div>
                        <div class="score-labels">
                          <span>0</span>
                          <span class="threshold-label">及格线 (6分)</span>
                          <span>10</span>
                        </div>
                      </a-card>
                    </a-col>
                  </a-row>
                </div>

                <div class="text-analysis">
                  <h3>技术评估</h3>
                  <a-card>
                    <p>{{ analysisData.technicalSummary }}</p>
                  </a-card>

                  <h3 class="section-title">沟通能力评估</h3>
                  <a-card>
                    <p>{{ analysisData.communicationSummary }}</p>
                  </a-card>

                  <h3 class="section-title">多模态表现评估</h3>
                  <a-card>
                    <p>{{ analysisData.multimodalSummary }}</p>
                  </a-card>
                </div>
              </div>

              <!-- 右侧对话记录 -->
              <div class="right-transcript-panel">
                <h3>面试问答记录</h3>
                <a-timeline class="interview-timeline">
                  <a-timeline-item v-for="(item, index) in parsedTechnicalQuestions" :key="index">
                    <div class="timeline-item interviewer">
                      <span class="speaker">面试官</span>
                      <div class="content">{{ item.question }}</div>
                    </div>
                    <div class="timeline-item candidate">
                      <span class="speaker">候选人</span>
                      <div class="content">{{ item.userAnswer }}</div>
                    </div>
                    <div class="timeline-item analysis">
                      <div class="analysis-header">
                        <span class="analysis-title">回答评分: {{ item.score }}</span>
                        <a-tag :color="getScoreColor(item.score)">{{
                          getScoreLevel(item.score)
                        }}</a-tag>
                      </div>
                      <div class="analysis-content">
                        <p><strong>点评:</strong> {{ item.remark }}</p>
                        <p><strong>建议:</strong> {{ item.suggest }}</p>
                      </div>
                    </div>
                  </a-timeline-item>
                </a-timeline>
              </div>
            </div>
          </a-tab-pane>

          <!-- 多模态分析标签页 -->
          <a-tab-pane key="multimodal" tab="多模态分析">
            <div class="analysis-content">
              <div class="multimodal-container">
                <h3>多模态行为分析</h3>
                <a-table
                  :dataSource="parsedMultimodalQuestions"
                  :columns="multimodalColumns"
                  :pagination="false"
                  bordered
                >
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'facialActions'">
                      <div class="multimodal-detail">
                        {{ record.facialActions }}
                      </div>
                    </template>
                    <template v-if="column.dataIndex === 'bodyMovements'">
                      <div class="multimodal-detail">
                        {{ record.bodyMovements }}
                      </div>
                    </template>
                    <template v-if="column.dataIndex === 'microExpression'">
                      <div class="multimodal-detail">
                        {{ record.microExpression }}
                      </div>
                    </template>
                    <template v-if="column.dataIndex === 'remark'">
                      <div class="multimodal-detail">
                        {{ record.ramark || record.remark }}
                      </div>
                    </template>
                  </template>
                </a-table>
              </div>
            </div>
          </a-tab-pane>

          <!-- 技能评估标签页 -->
          <a-tab-pane key="skills" tab="技能评估">
            <div class="analysis-content">
              <div class="skills-container">
                <!-- 技术问题解答质量 -->
                <div class="skills-section">
                  <h3>技术问题解答质量</h3>
                  <a-table
                    :dataSource="parsedTechnicalQuestions"
                    :columns="questionColumns"
                    :pagination="false"
                    bordered
                  >
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.dataIndex === 'score'">
                        <div class="score-display">
                          <span class="score-value" :style="{ color: getScoreColor(record.score) }"
                            >{{ record.score }} 分</span
                          >
                          <div class="score-bar-mini">
                            <div
                              class="score-bar-fill"
                              :style="{
                                width: `${record.score * 10}%`,
                                backgroundColor: getScoreColor(record.score),
                              }"
                            ></div>
                            <div class="score-threshold-mini"></div>
                          </div>
                        </div>
                      </template>
                    </template>
                  </a-table>
                </div>
              </div>
            </div>
          </a-tab-pane>

          <!-- 改进建议标签页 -->
          <a-tab-pane key="improvement" tab="改进建议">
            <div class="analysis-content">
              <div class="improvement-container">
                <!-- 总体改进建议 -->
                <div class="improvement-overview">
                  <a-card title="总体改进方向" class="overview-card">
                    <div class="improvement-summary">
                      <p>
                        根据面试表现，候选人在技术广度和深度方面有一定基础，但在表达能力和回答结构方面需要进一步提升。以下是主要改进方向：
                      </p>
                      <a-alert
                        message="重点提升领域：技术表达能力与回答结构"
                        type="info"
                        show-icon
                        style="margin: 16px 0"
                      />
                    </div>
                  </a-card>
                </div>

                <!-- 详细改进建议 -->
                <div class="improvement-details">
                  <h3>详细改进建议</h3>
                  <a-collapse v-model:activeKey="activeCollapseKey">
                    <a-collapse-panel
                      v-for="(item, index) in improvementSuggestions"
                      :key="index.toString()"
                      :header="item.title"
                    >
                      <div class="improvement-item">
                        <p class="item-desc">{{ item.description }}</p>
                        <div class="item-actions">
                          <h4>建议行动方案</h4>
                          <a-steps direction="vertical" size="small" :current="-1">
                            <a-step
                              v-for="(action, idx) in item.actions"
                              :key="idx"
                              :title="action.title"
                              :description="action.description"
                            />
                          </a-steps>
                        </div>
                        <div class="item-resources">
                          <h4>推荐学习资源</h4>
                          <a-list size="small">
                            <a-list-item v-for="(resource, idx) in item.resources" :key="idx">
                              <template #actions>
                                <a :href="resource.link" target="_blank">查看</a>
                              </template>
                              <a-list-item-meta
                                :title="resource.title"
                                :description="resource.type"
                              />
                            </a-list-item>
                          </a-list>
                        </div>
                      </div>
                    </a-collapse-panel>
                  </a-collapse>
                </div>

                <!-- 职业发展路径 -->
                <div class="career-path">
                  <h3>职业发展路径建议</h3>
                  <a-card>
                    <a-timeline mode="alternate">
                      <a-timeline-item v-for="(step, index) in careerPath" :key="index">
                        <template #dot>
                          <component :is="step.icon" style="font-size: 16px" />
                        </template>
                        <div class="career-step">
                          <h4>{{ step.title }}</h4>
                          <p>{{ step.description }}</p>
                        </div>
                      </a-timeline-item>
                    </a-timeline>
                  </a-card>
                </div>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>

      <!-- 无数据提示 -->
      <a-empty v-if="!loading && !analysisData" description="暂无分析数据" />
    </a-spin>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const router = useRouter()
const route = useRoute()
const id = route.query.id

const goBack = () => {
  router.go(-1)
}

import {
  Tabs as ATabs,
  TabPane as ATabPane,
  Card as ACard,
  List as AList,
  ListItem as AListItem,
  ListItemMeta as AListItemMeta,
  Timeline as ATimeline,
  TimelineItem as ATimelineItem,
  Progress as AProgress,
  Table as ATable,
  Row as ARow,
  Col as ACol,
  Descriptions as ADescriptions,
  DescriptionsItem as ADescriptionsItem,
  Alert as AAlert,
  Collapse as ACollapse,
  CollapsePanel as ACollapsePanel,
  Steps as ASteps,
  Step as AStep,
  Tag as ATag,
  Spin as ASpin,
  Empty as AEmpty,
} from 'ant-design-vue'
import {
  CheckCircleFilled,
  ExclamationCircleFilled,
  CodeOutlined,
  BookOutlined,
  RocketOutlined,
  ToolOutlined,
  TrophyOutlined,
  ArrowLeftOutlined,
} from '@ant-design/icons-vue'
import { getTecInterviewAnalyzeResultUsingGet } from '@/api/tecInterviewController'

const activeTab = ref('summary')
const activeCollapseKey = ref(['0'])
const loading = ref(true)
const analysisData = ref(null)

// 解析技术问题数据
const parsedTechnicalQuestions = computed(() => {
  if (!analysisData.value || !analysisData.value.technicalQuestions) return []
  try {
    return JSON.parse(analysisData.value.technicalQuestions)
  } catch (e) {
    console.error('解析技术问题数据出错:', e)
    return []
  }
})

// 解析多模态问题数据
const parsedMultimodalQuestions = computed(() => {
  if (!analysisData.value || !analysisData.value.multimodalQuestions) return []
  try {
    return JSON.parse(analysisData.value.multimodalQuestions)
  } catch (e) {
    console.error('解析多模态问题数据出错:', e)
    return []
  }
})

// 解析分数数据
const parsedScores = computed(() => {
  if (!analysisData.value || !analysisData.value.scores) return []
  try {
    return JSON.parse(analysisData.value.scores).map((score) => parseFloat(score))
  } catch (e) {
    console.error('解析分数数据出错:', e)
    return []
  }
})

// 判断面试是否通过（所有题目分数都超过6分）
const isInterviewPassed = computed(() => {
  if (!analysisData.value || !analysisData.value.totalScore) return false
  return parseFloat(analysisData.value.totalScore) >= 60
})

// 多模态分析表格列定义
const multimodalColumns = [
  {
    title: '问题',
    dataIndex: 'question',
    key: 'question',
    width: 250,
    customRender: ({ index }) => {
      if (!parsedTechnicalQuestions.value || parsedTechnicalQuestions.value.length <= index) {
        return `问题 ${index + 1}`
      }
      return parsedTechnicalQuestions.value[index].question
    },
  },
  {
    title: '微表情',
    dataIndex: 'microExpression',
    key: 'microExpression',
    width: 150,
  },
  {
    title: '面部表情',
    dataIndex: 'facialActions',
    key: 'facialActions',
    width: 250,
  },
  {
    title: '肢体动作',
    dataIndex: 'bodyMovements',
    key: 'bodyMovements',
    width: 250,
  },
  {
    title: '语音情绪',
    dataIndex: 'audioEmotion',
    key: 'audioEmotion',
    width: 120,
    align: 'center',
  },
  {
    title: '点评',
    dataIndex: 'remark',
    key: 'remark',
  },
]

// 技能评估表格列定义
const questionColumns = [
  {
    title: '问题',
    dataIndex: 'question',
    key: 'question',
    width: '30%',
  },
  {
    title: '回答',
    dataIndex: 'userAnswer',
    key: 'userAnswer',
    width: '30%',
  },
  {
    title: '评分',
    dataIndex: 'score',
    key: 'score',
    width: '15%',
    align: 'center',
  },
  {
    title: '点评',
    dataIndex: 'remark',
    key: 'remark',
    width: '25%',
  },
]

// 改进建议详情
const improvementSuggestions = ref([
  {
    title: '提升技术表达能力',
    description: '候选人在技术概念表达上需要进一步提升，特别是在结构化表达和使用专业术语方面。',
    actions: [
      {
        title: '练习技术演讲',
        description: '参加技术分享会或录制技术讲解视频，提升表达能力',
      },
      {
        title: '结构化思维训练',
        description: '使用STAR法则或金字塔原理组织回答，提高表达逻辑性',
      },
      {
        title: '专业术语使用',
        description: '整理常用技术术语表，确保准确使用专业词汇',
      },
    ],
    resources: [
      {
        title: '技术演讲的艺术',
        type: '在线课程',
        link: '#',
      },
      {
        title: '程序员沟通技巧',
        type: '电子书',
        link: '#',
      },
      {
        title: '技术面试表达指南',
        type: '技术博客',
        link: '#',
      },
    ],
  },
  {
    title: '深化核心概念理解',
    description: '候选人对一些基础概念有了解，但需要更深入地理解其原理和应用场景。',
    actions: [
      {
        title: '系统学习基础知识',
        description: '重新学习Java核心概念，特别是并发和集合框架',
      },
      {
        title: '源码阅读',
        description: '阅读HashMap和ConcurrentHashMap的源码，理解实现细节',
      },
      {
        title: '实践应用',
        description: '在实际项目中应用不同的集合类，体会其性能差异',
      },
    ],
    resources: [
      {
        title: 'Java并发编程实战',
        type: '技术书籍',
        link: '#',
      },
      {
        title: 'Java集合框架深度解析',
        type: '视频教程',
        link: '#',
      },
      {
        title: 'HashMap与ConcurrentHashMap源码分析',
        type: '技术文档',
        link: '#',
      },
    ],
  },
  {
    title: '提升面试应对技巧',
    description: '候选人在面试过程中的表现可以进一步优化，包括情绪控制和回答节奏。',
    actions: [
      {
        title: '模拟面试训练',
        description: '进行模拟面试，录制视频并分析自己的表现',
      },
      {
        title: '回答节奏控制',
        description: '练习控制语速和停顿，提高表达清晰度',
      },
      {
        title: '肢体语言优化',
        description: '注意面部表情和手势，展现自信和专业',
      },
    ],
    resources: [
      {
        title: '程序员面试金典',
        type: '参考书籍',
        link: '#',
      },
      {
        title: '技术面试心理学',
        type: '在线课程',
        link: '#',
      },
      {
        title: '面试官视角：如何评价候选人',
        type: '技术博客',
        link: '#',
      },
    ],
  },
])

// 职业发展路径
const careerPath = ref([
  {
    title: '巩固基础知识',
    description: '深入学习Java核心概念，特别是并发编程和集合框架',
    icon: CodeOutlined,
  },
  {
    title: '提升表达能力',
    description: '练习技术表达和沟通，提高面试和日常工作中的表达清晰度',
    icon: ToolOutlined,
  },
  {
    title: '项目实践',
    description: '参与实际项目，将理论知识应用到实践中，积累经验',
    icon: RocketOutlined,
  },
  {
    title: '技术深耕',
    description: '选择感兴趣的技术方向深入研究，形成专业特长',
    icon: BookOutlined,
  },
  {
    title: '技术领导力',
    description: '发展技术管理和团队协作能力，为高级开发工程师角色做准备',
    icon: TrophyOutlined,
  },
])

/**
 * 根据分数获取颜色
 * @param {number} score 分数
 * @returns {string} 颜色代码
 */
const getScoreColor = (score) => {
  if (score >= 8) return '#52c41a'
  if (score >= 7) return '#1890ff'
  if (score >= 6) return '#faad14'
  return '#f5222d'
}

/**
 * 根据分数获取等级
 * @param {number} score 分数
 * @returns {string} 等级文本
 */
const getScoreLevel = (score) => {
  if (score >= 8) return '优秀'
  if (score >= 7) return '良好'
  if (score >= 6) return '及格'
  return '不及格'
}

/**
 * 根据总分获取颜色
 * @param {number|string} score 总分
 * @returns {string} 颜色代码
 */
const getTotalScoreColor = (score) => {
  const numScore = typeof score === 'string' ? parseFloat(score) : score
  if (numScore >= 80) return '#52c41a'
  if (numScore >= 70) return '#1890ff'
  if (numScore >= 60) return '#faad14'
  return '#f5222d'
}

/**
 * 获取面试分析数据
 */
const fetchAnalysisData = async () => {
  if (!id) {
    loading.value = false
    return
  }

  loading.value = true
  try {
    const response = await getTecInterviewAnalyzeResultUsingGet({
      aiInterviewId: id,
    })

    if (response.code === 0 && response.data) {
      analysisData.value = response.data
    } else {
      console.error('获取面试分析数据失败:', response.message)
    }
  } catch (error) {
    console.error('获取面试分析数据出错:', error)
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAnalysisData()
})
</script>

<style scoped>
.interview-analysis-container {
  overflow-y: auto;
  max-height: 100vh;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(to right, #f8f9fa 0%, #f1f3f5 100%);
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.analysis-content-wrapper {
  flex: 1;
}

.analysis-tabs {
  margin-bottom: 16px;
  background: white;
  padding: 0 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.analysis-tabs :deep(.ant-tabs-nav) {
  margin: 0;
}

.analysis-content {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.left-analysis-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-width: 380px;
}

.right-transcript-panel {
  width: 45%;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  align-self: flex-start;
}

.scores-overview,
.text-analysis {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.scores-overview {
  margin-bottom: 0;
}

.score-card {
  margin-bottom: 16px;
}

.score-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.question-index {
  font-weight: 500;
  color: #333;
}

.section-title {
  margin-top: 20px;
  margin-bottom: 12px;
  color: #333;
  font-size: 16px;
}

.interview-timeline {
  margin-top: 16px;
}

.timeline-item {
  padding: 12px 16px;
  border-radius: 6px;
  margin-bottom: 8px;
}

.timeline-item.interviewer {
  background-color: #f0f7ff;
  border-left: 3px solid #1890ff;
}

.timeline-item.candidate {
  background-color: #f6ffed;
  border-left: 3px solid #52c41a;
}

.timeline-item.analysis {
  background-color: #fcfcfc;
  border-left: 3px solid #722ed1;
  margin-bottom: 24px;
}

.analysis-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.analysis-title {
  font-weight: 500;
  color: #333;
}

.analysis-content {
  color: #666;
}

.speaker {
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
  display: block;
}

.content {
  color: #666;
  line-height: 1.6;
}

/* 多模态分析样式 */
.multimodal-container {
  width: 100%;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.multimodal-container h3 {
  margin-bottom: 16px;
}

.multimodal-detail {
  max-width: 250px;
}

/* 技能评估页样式 */
.skills-container {
  width: 100%;
}

.skills-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.skills-section h3 {
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
}

/* 改进建议页样式 */
.improvement-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.improvement-overview,
.improvement-details,
.career-path {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.improvement-details h3,
.career-path h3 {
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
}

.improvement-summary {
  line-height: 1.6;
  color: #666;
}

.improvement-summary p {
  margin-bottom: 12px;
}

.improvement-item {
  padding: 8px 0;
}

.item-desc {
  font-size: 14px;
  line-height: 1.6;
  color: #666;
  margin-bottom: 16px;
}

.item-actions,
.item-resources {
  margin-top: 16px;
}

.item-actions h4,
.item-resources h4 {
  font-size: 14px;
  color: #333;
  margin-bottom: 12px;
}

.career-step {
  padding: 8px 0;
}

.career-step h4 {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

.career-step p {
  font-size: 13px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .analysis-content {
    flex-direction: column;
  }

  .right-transcript-panel {
    width: 100%;
  }

  .left-analysis-panel {
    min-width: unset;
  }
}

@media (max-width: 576px) {
  .interview-analysis-container {
    padding: 16px;
  }
}

.score-bar-container {
  position: relative;
  height: 10px;
  background-color: #f0f0f0;
  border-radius: 5px;
  margin: 10px 0;
  overflow: hidden;
}

.score-bar {
  height: 100%;
  border-radius: 5px;
  transition: width 0.5s ease;
}

.score-threshold {
  position: absolute;
  top: 0;
  width: 2px;
  height: 100%;
  background-color: #000;
  z-index: 1;
}

.score-labels {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

.threshold-label {
  position: absolute;
  left: 60%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #666;
}

.score-number {
  font-size: 24px;
  font-weight: bold;
}

.total-score {
  margin-top: 16px;
  font-size: 16px;
  text-align: center;
}

.score-unit {
  font-size: 12px;
  color: #666;
}

.result-summary {
  margin-bottom: 20px;
}

.score-display {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.score-value {
  font-weight: bold;
  font-size: 14px;
}

.score-bar-mini {
  position: relative;
  height: 6px;
  background-color: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
  width: 100%;
}

.score-bar-fill {
  height: 100%;
  border-radius: 3px;
}

.score-threshold-mini {
  position: absolute;
  top: 0;
  left: 60%;
  width: 2px;
  height: 100%;
  background-color: #000;
  z-index: 1;
}
</style>

